import json
import logging
import re
import jsonpath
from common.enums.common_enums import TokenType
from common.utils import db_util
from common.utils.assert_util import query_db_as_dict, assert_response
from common.utils.db_util import DBUtil
from common.utils.file_util import CacheUtil
from common.utils.http_util import do_simple_request

logger = logging.getLogger(__name__)


def execute(case, cache_key):
    logger.info(f'场景：{case[0][0]}，开始执行')
    for items in case:
        item = items[1]
        if item['operate_type'] in ['http', 'HTTP']:
            logger.info(f'步骤{item["step"]}：{item["name"]}')
            response = do_simple_request(item, token_type=TokenType.RABBIT_PLATFORM_TOKEN, cache_key=cache_key)
            logger.info(f'响应结果为：{response}')
            assert_response(item['expect'], response)
            if item['out_params']:
                out_params_list = re.split(r'\)\s*[,，]*\s*\n*\s*', item['out_params'])
                out_params_list = [i[1:] for i in out_params_list if i != '']
                out_params_list_transform = []
                for i in out_params_list:
                    param_name_value = re.split(r',|，', i)
                    out_params_list_transform.append(param_name_value)
                out_params_dict = {}
                for out_param in out_params_list_transform:
                    # 出参参数名
                    var_name = out_param[1]
                    # 出参参数值
                    var_value = jsonpath.jsonpath(response, out_param[0])[0]
                    out_params_dict.update({var_name: var_value})
                CacheUtil.update({cache_key: out_params_dict})
        elif item['operate_type'] in ['db_before', 'db_check', 'db_clean']:
            # 加载json数组
            db_info = json.loads(item['db_info'])
            logger.info(f'步骤{item["step"]}：{item["name"]}')
            for one_sql in db_info:
                sql = str(one_sql['sql']).strip()
                # 缓存变量
                params = re.findall(r'\${(.*?)}', sql)
                for param in params:
                    sql = sql.replace('${' + param + '}', str(CacheUtil.result[cache_key][param]))
                one_sql.update({'sql': sql})
                logger.info(
                    f'数据库名为：{one_sql["dbname"]}，数据库类型为：{one_sql["dbtype"]}，sql语句为：{one_sql["sql"]}')
                conn = DBUtil(one_sql['dbtype'], one_sql['dbname'])
                if sql.lower().startswith('select'):
                    db_result = query_db_as_dict(**one_sql)[0]
                elif sql.lower().startswith('insert'):
                    db_result = conn.execute_insert(sql)
                elif sql.lower().startswith('delete'):
                    db_result = conn.execute_delete(sql)
                elif sql.lower().startswith('update'):
                    db_result = conn.execute_update(sql)
                logger.info(f'数据库操作执行结果为：{db_result}')
                if item['operate_type'] == 'db_before':
                    CacheUtil.update({cache_key: db_result})
                elif item['operate_type'] == 'db_check':
                    assert_response(item['expect'], db_result)
                elif item['operate_type'] == 'db_clean':
                    logger.info(item['name'] + '完成')


if __name__ == '__main__':
    sql = 'select id,name,project_id from t_api where id = ${id} and name = ${name}'
    # pattern_cache = re.compile(r'.*\${(.*)}.*')
    # match_cache = re.match(pattern_cache, sql)
    # groups = []
    # if match_cache:
    #     groups = match_cache.groups()
    pattern = r'\${(.*?)}'
    params = re.findall(pattern, sql)
    for param in params:
        sql = sql.replace('${' + param + '}', param + '11')
    print(sql)
